#include "Texture2D.hpp"
#include <QImage>
#include <QGLWidget>

Texture2D::Texture2D()
{
}

Texture2D::~Texture2D()
{
    destroy();
}

void        Texture2D::bind()
{
    glBindTexture(GL_TEXTURE_2D, _id);
}

void        Texture2D::unbind()
{
    glBindTexture(GL_TEXTURE_2D, 0);
}

void        Texture2D::enable()
{
    glEnable(GL_TEXTURE_2D);
}

void        Texture2D::disable()
{
    glDisable(GL_TEXTURE_2D);
}

void        Texture2D::load()
{
    load(_path);
}

#include <iostream>

void        Texture2D::load(std::string const& path)
{
    _path = path;

    QImage  image;
    image.load(_path.data());

    image = QGLWidget::convertToGLFormat(image);

    glGenTextures(1, &_id);
    glBindTexture(GL_TEXTURE_2D, _id);
    glTexImage2D(GL_TEXTURE_2D, 0, 4, image.width(), image.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, image.bits());
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, _minFilter);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, _magFilter);
    glBindTexture(GL_TEXTURE_2D, 0);
    _loaded = true;
}

void        Texture2D::destroy()
{
    if (_loaded == true)
    {
        glDeleteTextures(1, &_id);
        _loaded = false;
    }
}
